﻿using System;
using System.Net;
using System.Net.Sockets;
using MessageLib.Frame;
using MessageLib.Frame.Base;

namespace MessageLib
{
	public class Udp
	{
		public event EventHandler<OnReciveEventArgs> OnRecive;
	    public event EventHandler<OnSendEventArgs> OnSend; 
		private readonly UdpClient _udpClient;
		private IPEndPoint _serverPoint;

		public Udp(IPEndPoint ipEndPoint)
		{
			_udpClient = new UdpClient();
			_serverPoint = ipEndPoint;
			_udpClient.Connect(_serverPoint);
			_udpClient.BeginReceive(ReciveCallback, null);
		}

		private void ReciveCallback(IAsyncResult ar)
		{
			var x = _udpClient.EndReceive(ar,ref _serverPoint);
			OnRecive?.Invoke(this, new OnReciveEventArgs
			{
				ReviceBytes = x,
                Frame = BaseFrame.Parse(x)
			});
			_udpClient.BeginReceive(ReciveCallback, null);
		}

		public void Send(BaseFrame frame)
		{
			_udpClient.BeginSend(frame.FrameData,frame.FrameData.Length, SendCallback, frame);
		}

		private void SendCallback(IAsyncResult ar)
		{
			var x =_udpClient.EndSend(ar);
		    OnSend?.Invoke(this, new OnSendEventArgs
		    {
		        SentCount = x,
                Frame = ar.AsyncState as BaseFrame
		    });
		}
	}

	public class OnReciveEventArgs : EventArgs
	{
        public BaseFrame Frame { get; set; }
		public byte[] ReviceBytes { get; set; }
	}

    public class OnSendEventArgs : EventArgs
    {
        public BaseFrame Frame { get; set; }
        public int SentCount { get; set; }
    }
}
